package com.sky.service.impl;

import com.sky.dto.VueTemplateAddRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.entity.FormTemplate;
import com.sky.entity.VueFormFieldConfig;
import com.sky.mapper.VueFormTemplateMapper;
import com.sky.mapper.VueFormFieldConfigMapper;
import com.sky.result.Result;
import com.sky.service.VueFormTemplateService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class VueFormTemplateServiceImpl implements VueFormTemplateService {
    private final VueFormTemplateMapper vueFormTemplateMapper;
    private final VueFormFieldConfigMapper vueFormFieldConfigMapper;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    @Transactional
    public Result addTemplate(VueTemplateAddRequest request) {
        FormTemplate formTemplate = new FormTemplate();
        formTemplate.setTemplateName(request.getTemplateName());
        formTemplate.setDescription(request.getDescription());
        // 使用 applicantGroupId 作为 fieldGroup
        formTemplate.setFieldGroup(request.getApplicantGroupId());  // 修改这里
        
        // 插入模板并获取ID
        vueFormTemplateMapper.insertFormTemplate(formTemplate);
        // 确保获取到了ID
        Long templateId = formTemplate.getId();
        if (templateId == null) {
            return Result.error("模板ID获取失败");
        }

        for (VueFormFieldConfig field : request.getApplicationFields()) {
            field.setTemplateId(templateId);
            field.setMaterialCategory(1);
            field.setFieldGroup(String.valueOf(request.getApplicantGroupId()));
            field.setMaterialType(field.getMaterialType());
            
            
            vueFormFieldConfigMapper.insertFormFieldConfig(field);
        }

        for (VueFormFieldConfig field : request.getMaterialFields()) {
            field.setTemplateId(templateId);
            field.setMaterialCategory(0);  // 修改这里：材料清单字段改为 0
            field.setFieldGroup(String.valueOf(request.getApplicantGroupId()));
            field.setMaterialType(field.getMaterialType());
            vueFormFieldConfigMapper.insertFormFieldConfig(field);
        }

        return Result.success();
    }

    @Override
    public Result getTemplateDetail(Long id) {
        // 1. 获取模板基本信息
        FormTemplate template = vueFormTemplateMapper.getTemplateById(id);
        if (template == null) {
            return Result.error("模板不存在");
        }

        // 2. 获取模板的所有字段配置
        List<VueFormFieldConfig> allFields = vueFormFieldConfigMapper.getFieldsByTemplateId(id);
        
        // 3. 区分申请表字段和材料清单字段
        List<VueFormFieldConfig> applicationFields = allFields.stream()
            .filter(field -> field.getMaterialCategory() == 1)
            .collect(Collectors.toList());
            
        List<VueFormFieldConfig> materialFields = allFields.stream()
            .filter(field -> field.getMaterialCategory() == 0)
            .collect(Collectors.toList());

        // 4. 构建返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("id", template.getId());
        result.put("templateName", template.getTemplateName());
        result.put("description", template.getDescription());
        result.put("applicationFields", applicationFields);
        result.put("materialFields", materialFields);

        return Result.success(result);
    }

    @Override
    @Transactional
    public Result updateTemplate(VueTemplateAddRequest request) {
        if (request.getId() == null) {
            return Result.error("模板ID不能为空");
        }

        // 1. 更新模板基本信息
        FormTemplate formTemplate = new FormTemplate();
        formTemplate.setId(request.getId());
        formTemplate.setTemplateName(request.getTemplateName());
        formTemplate.setDescription(request.getDescription());
        formTemplate.setFieldGroup(request.getApplicantGroupId());  // 添加这行，更新适用人群
        vueFormTemplateMapper.updateFormTemplate(formTemplate);

        // 2. 删除原有的字段配置
        vueFormFieldConfigMapper.deleteByTemplateId(request.getId());

        // 3. 重新添加字段配置
        // 处理申请表字段
        for (VueFormFieldConfig field : request.getApplicationFields()) {
            field.setTemplateId(request.getId());
            field.setMaterialCategory(1);
            field.setFieldGroup(String.valueOf(request.getApplicantGroupId()));
            vueFormFieldConfigMapper.insertFormFieldConfig(field);
        }

        // 处理材料清单字段
        for (VueFormFieldConfig field : request.getMaterialFields()) {
            field.setTemplateId(request.getId());
            field.setMaterialCategory(0);
            field.setFieldGroup(String.valueOf(request.getApplicantGroupId()));
            vueFormFieldConfigMapper.insertFormFieldConfig(field);
        }

        return Result.success();
    }

    @Override
    @Transactional
    public Result deleteTemplate(Long id) {
        try {
            // 先删除关联的字段配置
            vueFormFieldConfigMapper.deleteByTemplateId(id);
            // 再删除模板
            vueFormTemplateMapper.deleteTemplateById(id);
            return Result.success();
        } catch (Exception e) {
            return Result.error("删除失败：" + e.getMessage());
        }
    }
}